<template>
  <Combination
    ref="comStationPriceRef"
    :items="comItem"
    :comData="ruleForm.data"
    :rules="comRules"
    :size="maxSize"
  ></Combination>
</template>

<script lang="ts" setup name="station-price">
import { FormRules } from 'element-plus';
import Combination from '@/components/combination/combination.vue';
import { queryCostTemplateByProtocolVersion } from '@/service/apis/pile';
import { queryDicByParent } from '@/service/apis/api';

const comStationPriceRef = ref();

interface Props {
  operatorId: string; // 运营商id
}
const prop = withDefaults(defineProps<Props>(), {
  operatorId: '',
});

let optionsS = reactive({
  version: [] as any,
  template: [] as any,
});
let maxSize = ref(1);

queryDicByParent({
  listDtos: ['protocolVersion'],
}).then((res: any) => {
  if (res) {
    optionsS.version = [...res.protocolVersion];
    comItem[0].props.options = [...res.protocolVersion];
    nextTick(() => {
      ruleForm.data.forEach((item: any, index: number) => {
        comStationPriceRef.value?.setOptions(index, 0, optionsS.version);
      });
      comStationPriceRef.value?.setOptions(0, 0, optionsS.version);
      comStationPriceRef.value?.setItemDatas(optionsS.version);
    });
    maxSize.value = res.protocolVersion.length;
  }
});

const getTemplateData = (value: string, index: number) => {
  if (!value) {
    comStationPriceRef.value?.setOptions(index, 1, []);
    return;
  }
  queryCostTemplateByProtocolVersion({
    value: value,
    operatorId: prop.operatorId || '',
  }).then((res: any) => {
    if (res) {
      optionsS.version = res.list ? [...res.list] : [];
      comStationPriceRef.value?.setOptions(index, 1, optionsS.version);
    }
  });
};

const changeVersion = (index: number, form: any) => {
  getTemplateData(form.data[index].protocolVersion, index);
  form.data[index].costTemplateId = undefined as any;
};
const changeTemplate = (index: number, form: any) => {
  if (form.data[index].costTemplateId) {
    form.items[index][2].props.disabled = false;
  } else {
    form.items[index][2].props.disabled = true;
  }
};

const ruleForm = reactive({
  data: [] as any,
});

const emit = defineEmits(['show-price']);
const comItem = reactive([
  {
    comName: 'select',
    label: '设备协议版本',
    labelWidth: 140,
    prop: 'protocolVersion',
    width: 220,
    isOnly: true,
    props: {
      options: optionsS.version,
      change: changeVersion,
    },
  },
  {
    comName: 'select',
    label: '选择计费模板',
    labelWidth: 120,
    prop: 'costTemplateId',
    width: 200,
    props: {
      remote: true,
      filterable: true,
      options: optionsS.template,
      change: changeTemplate,
    },
  },
  {
    comName: 'button',
    className: 'button-wrap',
    prop: 'btn1',
    width: 100,
    props: {
      value: '查看计费',
      type: 'primary',
      plain: true,
      disabled: true,
      click: (index: number, row: any) => {
        console.log('ddd', index, row);
        emit('show-price', row.data[index].costTemplateId);
      },
    },
  },
]);

const comRules = reactive<FormRules>({
  protocolVersion: [
    {
      required: true,
      message: '请选择设备协议版本',
      trigger: ['blur', 'change'],
    },
  ],
  costTemplateId: [
    {
      required: true,
      message: '请选择设备协议版本',
      trigger: ['blur', 'change'],
    },
  ],
});

const getData = async () => {
  if (!comStationPriceRef.value) return;
  try {
    await Promise.all([comStationPriceRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comStationPriceRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }

  const data = comStationPriceRef.value?.getData();
  return data;
};

const setData = (data: any) => {
  ruleForm.data = [];
  const items = comStationPriceRef.value.getItems();
  data.forEach((item: any, index: number) => {
    getTemplateData(item.protocolVersion, index);
    ruleForm.data.push({
      protocolVersion: item.protocolVersion,
      costTemplateId: item.costTemplateId,
      btn1: 'false',
    });
    nextTick(() => {
      items[index][2].props.disabled = false;
    });
  });
};

const updateTemplate = () => {
  const data = comStationPriceRef.value?.getData();
  const items = comStationPriceRef.value?.getItems();
  if (data && data.length > 0) {
    data.forEach((item: any, index: number) => {
      if (item.protocolVersion) {
        item.costTemplateId = '';
        items[index][2].props.disabled = true;
        getTemplateData(item.protocolVersion, index);
      }
    });
  }
};

watch(
  () => prop.operatorId,
  () => {
    updateTemplate();
  }
);

defineExpose({
  getData,
  setData,
});
</script>